<template>
  <div class="content">
    <dt-search ref="search">
      <Button type="primary" v-if="unlocking('0207050302')" @click='onExport'>导出</Button>
      <Button type="primary" v-if="unlocking('0207050301')" @click='onAdjust'>预估调整</Button>
    </dt-search>
    
    <dt-grid ref="table" page :onFetch='onFetch' />
    
    <upload-modal ref="upload" @success="onSuccess" />
	</div>
</template>

<script>
  import moment from 'moment'
  import uploadModal from './components/upload-modal.vue'
  import Column from './opt/Column.js'
  import SearchOpt from './opt/SearchOpt.js'
  import financialMgr from '@/biz/report/financialReport.js'
  
  export default {
    components: {
      uploadModal
    },
    data() {
      return {
        search: {}
      }
    },
    mounted() {
      this.$refs.table.init(this, new Column())
      this.$refs.search.init(this.$refs.table, new SearchOpt(), {
        startDate: moment(new Date()).format('YYYY-MM') + '-01',
        endDate: moment(new Date()).format('YYYY-MM-DD')
      })
      this.$refs.table.fetch()
    },
    methods: {
      onFetch(data) {
        if (data.startDate && data.endDate && !this.validateDate(data.startDate, data.endDate)) {
          return Promise.reject()
        }
        this.search = data
        return financialMgr.summaryList(data)
      },
      onExport() {
        financialMgr.summaryExport({
          startDate: this.search.startDate,
          endDate: this.search.endDate,
          orgIds: this.search.orgIds || [],
          housesId: this.search.housesId || null,
          customerName: this.search.customerName || null,
          contractorName: this.search.contractorName || null,
        })
      },
      onAdjust() {
        this.$refs.upload.show({
          startDate: this.search.startDate,
          endDate: this.search.endDate,
          orgIds: this.search.orgIds || [],
          housesId: this.search.housesId || null,
          customerName: this.search.customerName || null,
          contractorName: this.search.contractorName || null,
        })
      },
      onSuccess() {
        this.$refs.table.fetch()
      },
      validateDate(startDate, endDate) {
        let y_start = new Date(startDate).getFullYear(),
            y_end = new Date(endDate).getFullYear(),
            m_start = new Date(startDate).getMonth() + 1,
            m_end = new Date(endDate).getMonth() + 1,
            d_start = new Date(startDate).getDate(),
            d_end = new Date(endDate).getDate()
        let month = (y_end - y_start) * 12 + (m_end - m_start)
        if (month > 6 || (month == 6 && d_end > d_start)) {
          this.$Message.error('签约日期跨度最大6个月')
          return false
        }
        return true
      },
    },
  }
</script>

<style lang="scss" scoped>
  .content {
    padding: 20px;
  }
</style>
